// 引入express框架
const express = require('express');
// 引入验证模块
// const Joi = require('@hapi/joi');
const Joi = require('joi');
// lodash模块
const _ = require('lodash');
// 创建对象路由
const todoRouter = express.Router();
// 导入todo集合构造函数
const Task = require('../model/task');

//查询数据库并返回数据
todoRouter.get('/task', async(req, res) => {
    const task = await Task.find();
    res.send(task);
});

// 查询未完成数据
todoRouter.get('/clearTask', async(req, res) => {
    const task = await Task.deleteMany({ completed: true });
    const result = await Task.find();
    res.send(result);
});

// 添加任务
todoRouter.post('/addTask', async(req, res) => {
    const { title } = req.body;
    // console.log(title);
    // const schema = Joi.object({
    //     title: Joi.string().min(1).max(20).required()
    // });
    const schema = {
        title: Joi.string().min(1).max(20).required()
    };
    // const { error } = schema.validate({ title: schema });
    const { error } = Joi.validate(req.body, schema);
    if (error) {
        // 将错误信息响应给客户端
        return res.status(400).send({ message: error.details[0].message })
    }
    // 创建任务
    const task = new Task({ title: title, completed: false });
    // 插入数据
    await task.save();
    // 响应
    setTimeout(() => {
        res.send(task);
    }, 500);
});

// 删除任务
todoRouter.get('/deleteTask', async(req, res) => {
    const { _id } = req.query;
    // console.log(_id);
    // 验证规则
    const schema = {
            _id: Joi.string().required().regex(/^[0-9a-fA-F]{24}$/)
        }
        // 验证客户端传递过来的请求参数 
    const { error } = Joi.validate(req.query, schema);
    // 验证失败
    if (error) {
        // 将错误信息响应给客户端
        return res.status(400).send({ message: error.details[0].message })
    }
    const result = await Task.findOneAndDelete({ _id: _id });
    res.send(result);
});

// 完成任务
todoRouter.post('/modifyTask', async(req, res) => {
    // const { _id, completed } = req.body;
    // console.log(_id, completed);
    // var result = await Task.updateOne({ completed: completed });
    // res.send(result);
    // 执行修改操作
    const task = await Task.findOneAndUpdate({ _id: req.body._id }, _.pick(req.body, ['title', 'completed']), { new: true })
        // 响应
    res.send(task);
});



// 将todo案例路由作为模块成员进行导出
module.exports = todoRouter;